package controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.GetTrackIp;

import model.TrackIp;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import data.Data;

@SuppressWarnings("serial")
public class TrackIpServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String path = ((HttpServletRequest)req).getRequestURI();
		String update = req.getParameter("update");
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	resp.getWriter().println("Bad request : "+req.getRequestURI());
        	resp.getWriter().close();
        	return ;
        	
        }

		// skip one token /sites/gooogle.com (remove sites)
		st.nextToken();
		String ip = st.nextToken().replaceAll("[^0-9.]+", "");
		if(ip!=null&&ip.length()>0&&Pattern.matches("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$", ip))
		{
			PersistenceManager psm = Data.get().getPersistenceManager();
			Key k = KeyFactory.createKey(TrackIp.class.getSimpleName(), ip);
			TrackIp trackIp=new TrackIp();
			trackIp.setIp(ip);
			try {
	        	trackIp = psm.getObjectById(TrackIp.class, k);
	        	
			} catch (JDOObjectNotFoundException e) {
				new GetTrackIp(trackIp);
			}
			req.setAttribute("trackIp", trackIp);
			try {
				req.getRequestDispatcher("/track_ip.jsp").forward(req, resp);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
	}
}
